/**
 * 
 * Definition for singly-linked list.*/


#include<iostream>
#include<vector>
using namespace std;
struct ListNode { 
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head==nullptr) return nullptr;
        ListNode *p1,*p2;    //双指针，p1当前元素的下一个，p2遍历相同元素
        ListNode *noValHead = new ListNode(-101);
        noValHead->next = head;
        ListNode *node = noValHead;
        p1 = p2 = node->next;
        while(p1 != nullptr) {
            while(p2!=nullptr && p2->val == p1->val) {
                p2 = p2->next;
            }//一直遍历到第一个不相同的元素，或者到达尾部
            if(p1->next != p2){
                node->val == p1->val ? node = p2 : node->next = p2;
                p1 = p2 = node->next;
            }else{
                node = node->next;
                p1 = p2 = node->next;
            }
        }
        return noValHead->next;
    }
};
int main(int argc, char** argv){

    vector<int>num = {0,0,0,0,0};
    ListNode *head = new ListNode(num[0]);
    ListNode *node = head;
    for(int i=1 ; i<num.size() ; i++){
        ListNode *temp = new ListNode(num[i]);
        node->next = temp;
        node = temp;
    }
    node->next =  nullptr;
    Solution *s = new Solution();
    ListNode *ans = s->deleteDuplicates(head);
    while (ans!= nullptr)
    {
        cout<< ans->val << " ";
        ans = ans->next;
    }
    cout<<endl;
    return 0;
}